import 'dart:async';
import 'dart:io';

import 'package:cave_flutter/config/whl_global_config.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/network/whl_network_config.dart';
import 'package:cave_flutter/routes/whl_app_pages.dart';
import 'package:cave_flutter/utils/whl_db_utils.dart';

import 'package:cave_flutter/utils/whl_rc_im_utils.dart';
import 'package:cave_flutter/utils/whl_user_utils.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter_udid/flutter_udid.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';

import '../../network/whl_network_utils.dart';

class WhlSplashLogic extends GetxController {
  StreamSubscription<ConnectivityResult>? _connectivitySubscription;
  final Connectivity _connectivity = Connectivity();
  bool isConnect = false;
  @override
  void onInit() {
    super.onInit();
    _connectivitySubscription = _connectivity.onConnectivityChanged.listen((ConnectivityResult result) {
      if (ConnectivityResult.none != result && !isConnect) {
        isConnect = true;
        // onCheckLogin();
      }
    });
    onCheckLogin();
  }
  @override
  void onClose() {
    _connectivitySubscription?.cancel();
    super.onClose();
  }

  onCheckLogin() async {
    String uuid = await FlutterUdid.udid;
    PackageInfo packageInfo = WHLGlobalConfig.packageInfo;
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    WhlNetWorkConfig config = WhlNetWorkConfig(
        packageName: packageInfo.packageName,
        versionName: packageInfo.version,
        appVersionCode: int.parse(packageInfo.buildNumber),
        deviceId: uuid,
        platform: Platform.isAndroid ? 'Android' : 'iOS',
        model: Platform.isAndroid ? (await deviceInfo.androidInfo).hardware : (await deviceInfo.iosInfo).model,
        successCode: '200',
        requestErrorTip: 'Network request failed',
        requestTimeoutTip: 'Network request timeout',
        noLoginCode: '401');
    WhlNetWorkUtils.instance.initConfig(config);
    // await onGetAppConfig();
    Future.delayed(const Duration(milliseconds: 500)).then((value) async {
      if (WhlUserUtils.isLogin()) {
        // await WhlDBUtils().initDB();
        if (WhlUserUtils.getUserInfoComplete()) {
          Get.offNamed(Routes.main);

        }else {
          Get.offNamed(Routes.completeUserInfo);
        }

        // onCheckToken();
        // onGetStrategy();
      } else {
        Get.offNamed(Routes.login);
      }
    });
  }

  onGetAppConfig() async {
    Map<String, dynamic> params = {'ver': WhlUserUtils.getAppConfig()['ver'] ?? 0};
    // ResponseData responseData = await WhlApi.getAppConfig.get(params);
    // if (responseData.isSuccess()) {
    //   if (responseData.data is Map) {
    //     WhlUserUtils.setAppConfig(responseData.data);
    //   }
    // }
  }
  onGetStrategy () async {
    // ResponseData responseData = await WhlApi.getStrategy.get({});
    // if (responseData.isSuccess()) {
    //   WHLGlobalConfig.userServiceAccountId = responseData.data?['userServiceAccountId'] ?? '';
    //   onGetCustomServiceUserInfo();
    //   List list = responseData.data?['reviewOfficialBlacklistUserIds'] ?? '';
    //   if (WhlUserUtils.getBlockList().isEmpty){
    //     WhlUserUtils.setBlockList(list.map((e) => e.toString()).toList());
    //   }
    // }
  }
  onGetCustomServiceUserInfo() async {
    Map<String, dynamic> params = {
      'userId': WHLGlobalConfig.userServiceAccountId,
    };
    // ResponseData responseData = await WhlApi.getUserInfo.get(params);
    // if (responseData.isSuccess()) {
    //   WHLGlobalConfig.userServiceAccountAvatar = responseData.data?['avatarUrl'] ?? '';
    //   // WhlUserUtils.saveUserInfo(responseData.data);
    // }
  }

  onCheckToken() async {
    // Map<String, dynamic> params = {'token': WhlNetWorkUtils.getAccessToken()};
    // ResponseData responseData = await WhlApi.isValidToken.post(params);
    // if (responseData.isSuccess()) {
    //   print('token有效');
    // } else {
    //   print('token无效');
    //   WhlNetWorkUtils.setAccessToken('');
    //   Get.offNamed(Routes.login);
    // }
  }
}
